package com.study.webapp.springThink.beandefinition;

import com.study.webapp.springThink.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Commit;
import org.springframework.util.StringUtils;

import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;

/**
 * @program: study
 *
 * @description:
 *
 * @author: heqiang
 *
 * @create: 2020-06-21 20:53
 **/
//3,通过import进行导入
@Import(AnnotationBeanDefinitionDemo.Config.class)
public class AnnotationBeanDefinitionDemo {


    public static void main(String[] args) {
        //创建beanFactory工厂
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册configuration配置类
        applicationContext.register(AnnotationBeanDefinitionDemo.class);

        //通过beanDefinition注册api实现
        //1，命名bean的注册方式
        registerUserBeanDefinition(applicationContext,"heqiang-user");
        //2,非命名方式注册
        registerUserBeanDefinition(applicationContext);

        //启动应用上下文
        applicationContext.refresh();

        System.out.println("Config类型中所有的bean："+applicationContext.getBeansOfType(Config.class));
        System.out.println("User类型中所有的bean："+applicationContext.getBeansOfType(User.class));

        //关闭上下文
        applicationContext.close();
    }


    public static void registerUserBeanDefinition(BeanDefinitionRegistry registry,String beanName) {

        BeanDefinitionBuilder beanDefinitionBuilder = genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("id",1).addPropertyValue("name","heqinag");

        if (StringUtils.hasText(beanName)) {
            //命名方式bean注册
            registry.registerBeanDefinition(beanName,beanDefinitionBuilder.getBeanDefinition());
        } else {
            //非命名方式bean注册
            BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(),registry);
        }
    }


    public static void registerUserBeanDefinition(BeanDefinitionRegistry registry) {
        registerUserBeanDefinition(registry,null);
    }




    /**
     * 1,@Bean方式定义
     */
    @Component
    public static class Config {

        @Bean
        public User user() {
            User user = new User();
            user.setId(1L);
            user.setName("heqiang");
            return user;
        }
    }
}
